﻿using BW.Mes.WinForms.BasicData;
using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static BW.Mes.WinForms.BasicData.MaterialForm;
using BW.Mes.WinForms;

namespace BW.Mes.WinForms.BasicData
{
    public partial class MaterialForm : DevExpress.XtraEditors.XtraForm
    {
        private readonly HttpClient _httpClient;
        private readonly string _materialApiBaseUrl = "http://120.26.197.100:8022";
        private bool _showDeletedMaterials = false; // 控制是否显示已删除的物料
        private List<MaterialModel> _allMaterials = new List<MaterialModel>(); // 保存所有数据

        public MaterialForm()
        {
            InitializeComponent();
            // 物料管理绿色斑马纹
            gridView1.OptionsView.EnableAppearanceEvenRow = true;
            gridView1.OptionsView.EnableAppearanceOddRow = true;
            gridView1.Appearance.EvenRow.BackColor = ColorTranslator.FromHtml("#d6ffe9");
            gridView1.Appearance.EvenRow.Options.UseBackColor = true;
            gridView1.Appearance.OddRow.BackColor = ColorTranslator.FromHtml("#e6fff6");
            gridView1.Appearance.OddRow.Options.UseBackColor = true;
            gridView1.Appearance.FocusedRow.BackColor = Color.Transparent;
            gridView1.Appearance.FocusedRow.Options.UseBackColor = false;
            gridView1.Appearance.HideSelectionRow.BackColor = Color.Transparent;
            gridView1.Appearance.HideSelectionRow.Options.UseBackColor = false;
            gridControl1.LookAndFeel.UseDefaultLookAndFeel = false;
            //初始化httpClient
            _httpClient = new HttpClient();
            _httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));


            // 窗体加载时获取数据
            pagerControl1.PageChanged += async (s, e2) =>
            {
                await LoadMaterialData(pagerControl1.PageIndex, pagerControl1.PageSize);
            };
            this.Load += async (s, e) =>
            {
                await LoadMaterialData(1, pagerControl1.PageSize);
            };
            
            // 设置网格的操作列
            SetupGridActionColumn();

            gridView1.CustomUnboundColumnData += gridView1_CustomUnboundColumnData;

            gridView1.OptionsSelection.MultiSelect = true;
            gridView1.OptionsSelection.MultiSelectMode = DevExpress.XtraGrid.Views.Grid.GridMultiSelectMode.CheckBoxRowSelect;
        }

        private void SetupGridActionColumn()
        {
            // 创建操作列
            var actionColumn = new DevExpress.XtraGrid.Columns.GridColumn();
            actionColumn.Caption = "操作";
            actionColumn.FieldName = "Action";
            actionColumn.UnboundType = DevExpress.Data.UnboundColumnType.Object;
            actionColumn.Visible = true;
            actionColumn.Width = 120;
            
            // 设置操作列的显示模板
            var buttonEdit = new DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit();
            buttonEdit.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.HideTextEditor;
            buttonEdit.Buttons.Clear();
            
            // 添加修改按钮
            buttonEdit.Buttons.Add(new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph) { Caption = "修改", Width = 50 });
            
            // 添加删除按钮
            buttonEdit.Buttons.Add(new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph) { Caption = "删除", Width = 50 });
            
            // 绑定按钮点击事件
            buttonEdit.ButtonClick += ButtonEdit_ButtonClick;
            
            // 添加操作列到网格
            actionColumn.ColumnEdit = buttonEdit;
            gridControl1.RepositoryItems.Add(buttonEdit);
            gridView1.Columns.Add(actionColumn);
        }

        private async void ButtonEdit_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            var rowHandle = gridView1.FocusedRowHandle;
            if (rowHandle < 0) return;
            var material = gridView1.GetRow(rowHandle) as MaterialModel;
            if (material == null) return;

            if (e.Button.Caption == "删除")
            {
                var confirm = XtraMessageBox.Show($"确定要删除物料 '{material.MaterialName}' 吗？", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (confirm != DialogResult.Yes) return;
                var (success, errorMsg) = await DeleteMaterial(material.Id);
                if (success)
                {
                    XtraMessageBox.Show("删除成功！", "操作成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    await LoadMaterialData(pagerControl1.PageIndex, pagerControl1.PageSize);
                }
                else
                {
                    XtraMessageBox.Show(errorMsg, "删除失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else if (e.Button.Caption == "修改")
            {
                var updateForm = new UpdateMaterialForm(material);
                if (updateForm.ShowDialog() == DialogResult.OK)
                {
                    await LoadMaterialData(pagerControl1.PageIndex, pagerControl1.PageSize);
                }
            }
        }

        private async Task LoadMaterialData(int pageIndex, int pageSize)
        {
            try
            {
                string url = $"T2/Material/GetMaterial?PageIndex={pageIndex}&PageSize={pageSize}";
                List<MaterialModel> data = null;
                int totalCount = pagerControl1.TotalCount;
                try
                {
                    var result = await GetApiDataAsync<MaterialPageResult>(url);
                    data = result?.pageDatas ?? new List<MaterialModel>();
                    totalCount = result?.totalCount ?? 0;
                }
                catch
                {
                    data = await GetApiDataAsync<List<MaterialModel>>(url);
                }
                gridControl1.DataSource = data;
                pagerControl1.TotalCount = totalCount;
                pagerControl1.PageIndex = pageIndex;
                pagerControl1.PageSize = pageSize;
                gridView1.PopulateColumns();
                gridView1.BestFitColumns();
                AfterBindMaterialData();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据失败: {ex.Message}\n{ex.StackTrace}", "错误");
            }
        }

        private async Task<T> GetApiDataAsync<T>(string endpoint)
        {
            try
            {
                HttpResponseMessage response = await _httpClient.GetAsync($"{_materialApiBaseUrl}/{endpoint}");
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<T>(responseBody);
            }
            catch (Exception)
            {
                // 反序列化失败时返回 default，避免异常抛出到外层
                return default(T);
            }
        }

        // 提交数据到API
        public async Task<bool> PostApiDataAsync<T>(string endpoint, T data)
        {
            try
            {
                string jsonData = JsonConvert.SerializeObject(data);
                HttpContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");
                HttpResponseMessage response = await _httpClient.PostAsync($"{_materialApiBaseUrl}/{endpoint}", content);
                response.EnsureSuccessStatusCode();
                return true;
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"提交数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }

        public class MaterialModel
        {
            public long Id { get; set; }
            /// <summary>
            /// 物料编号
            /// </summary>
            [DisplayName("物料编号")]
            public string MaterialCode { get; set; }
            /// <summary>
            /// 物料名称
            /// </summary>
            [DisplayName("物料名称")]
            public string MaterialName { get; set; }
            /// <summary>
            /// 物料类型
            /// </summary>
            [DisplayName("物料类型")]
            public string MaterialType { get; set; }
            /// <summary>
            /// 工艺路线
            /// </summary>
            [DisplayName("工艺路线")]
            public string Routing { get; set; }
            /// <summary>
            /// 物料描述
            /// </summary>
            [DisplayName("物料描述")]
            public string MaterialMsg { get; set; }
            [DisplayName("创建人")]
            public string CreatedBy { get; set; }
            [DisplayName("创建时间")]
            public DateTime CreatedAt { get; set; } = DateTime.Now;
            [DisplayName("更新时间")]
            public DateTime? UpdatedAt { get; set; }
            public bool IsDeleted { get; set; } // 新增字段
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            LoadMaterialData(1, pagerControl1.PageSize);
        }

        private void gridControl1_Click(object sender, EventArgs e)
        {

        }

        private async void simpleButton1_Click(object sender, EventArgs e)
        {
            var form = new AddMaterialGroupForm();
            if (form.ShowDialog() == DialogResult.OK)
            {
                await LoadMaterialData(1, pagerControl1.PageSize);
            }
        }

        private async void simpleButtonModify_Click(object sender, EventArgs e)
        {
            var rowHandle = gridView1.FocusedRowHandle;
            if (rowHandle < 0)
            {
                XtraMessageBox.Show("请先选择要修改的物料！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            var material = gridView1.GetRow(rowHandle) as MaterialModel;
            if (material == null)
            {
                XtraMessageBox.Show("未获取到物料信息！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            
            var updateForm = new UpdateMaterialForm(material);
            if (updateForm.ShowDialog() == DialogResult.OK)
            {
                await LoadMaterialData(pagerControl1.PageIndex, pagerControl1.PageSize);
            }
        }

        private async void simpleButtonDelete_Click(object sender, EventArgs e)
        {
            var selectedRows = gridView1.GetSelectedRows();
            if (selectedRows.Length == 0)
            {
                XtraMessageBox.Show("请先选择要删除的物料！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            var confirm = XtraMessageBox.Show($"确定要删除选中的 {selectedRows.Length} 个物料吗？", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (confirm != DialogResult.Yes) return;

            int successCount = 0;
            int failureCount = 0;
            string firstError = null;

            foreach (var rowHandle in selectedRows)
            {
                var material = gridView1.GetRow(rowHandle) as MaterialModel;
                if (material != null)
                {
                    var (success, errorMsg) = await DeleteMaterial(material.Id);
                    if (success)
                    {
                        successCount++;
                    }
                    else
                    {
                        failureCount++;
                        if (firstError == null)
                            firstError = errorMsg;
                    }
                }
            }

            await LoadMaterialData(pagerControl1.PageIndex, pagerControl1.PageSize);

            if (successCount > 0 && failureCount == 0)
            {
                XtraMessageBox.Show($"成功删除 {successCount} 个物料。", "操作成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else if (successCount > 0 && failureCount > 0)
            {
                XtraMessageBox.Show($"成功删除 {successCount} 个物料，{failureCount} 个物料删除失败。\n第一个失败原因：{firstError}", "操作完成", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else if (failureCount > 0)
            {
                XtraMessageBox.Show(firstError, "删除失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async Task<(bool, string)> DeleteMaterial(long id)
        {
            try
            {
                var response = await _httpClient.PutAsync($"{_materialApiBaseUrl}/T2/Material/DeleteMaterial?id={id}", null);
                var responseContent = await response.Content.ReadAsStringAsync();
                if (response.IsSuccessStatusCode)
                {
                    var apiResult = JsonConvert.DeserializeObject<ApiResult<object>>(responseContent);
                    if (apiResult != null && apiResult.code == 200)
                    {
                        return (true, null);
                    }
                    else
                    {
                        string errorMessage = apiResult?.message ?? "删除失败，但未返回具体错误信息。";
                        return (false, errorMessage);
                    }
                }
                else
                {
                    string errorMessage = $"HTTP错误: {response.StatusCode}";
                    try
                    {
                        var errorResult = JsonConvert.DeserializeObject<ApiResult<object>>(responseContent);
                        if (errorResult != null && !string.IsNullOrEmpty(errorResult.message))
                        {
                            errorMessage = errorResult.message;
                        }
                    }
                    catch { }
                    return (false, errorMessage);
                }
            }
            catch (Exception ex)
            {
                return (false, $"删除时发生异常: {ex.Message}");
            }
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            LoadMaterialData(pagerControl1.PageIndex, pagerControl1.PageSize);
        }

        private void EnsureSerialNumberColumn()
        {
            if (gridView1.Columns["序号"] == null)
            {
                var col = gridView1.Columns.AddField("序号");
                col.Caption = "序号";
                col.UnboundType = DevExpress.Data.UnboundColumnType.Integer;
                col.Visible = true;
                col.VisibleIndex = 0;
            }
            else
            {
                gridView1.Columns["序号"].Visible = true;
                gridView1.Columns["序号"].VisibleIndex = 0;
            }
        }

        private void gridView1_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            if (e.Column.FieldName == "序号" && e.IsGetData)
            {
                e.Value = e.ListSourceRowIndex + 1;
            }
        }

        private void AfterBindMaterialData()
        {
            EnsureSerialNumberColumn();
            string[] idNames = { "Id", "ID", "id", "MaterialId", "MaterialID", "materialId", "IsDeleted" };
            foreach (var name in idNames)
            {
                var idColumn = gridView1.Columns[name];
                if (idColumn != null) idColumn.Visible = false;
            }
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            LoadMaterialData(1, pagerControl1.PageSize);
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            simpleButtonDelete_Click(sender, e);
        }

        private void btnModify_Click(object sender, EventArgs e)
        {
            var selectedRows = gridView1.GetSelectedRows();
            if (selectedRows.Length != 1)
            {
                XtraMessageBox.Show("请只选择一条要修改的物料！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            var material = gridView1.GetRow(selectedRows[0]) as MaterialModel;
            if (material == null)
            {
                XtraMessageBox.Show("未获取到物料信息！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
         
            var updateForm = new UpdateMaterialForm(material);
            if (updateForm.ShowDialog() == DialogResult.OK)
            {
                LoadMaterialData(pagerControl1.PageIndex, pagerControl1.PageSize);
            }
        }
    }

    public class ApiResult<T>
    {
        public int code { get; set; }
        public int success { get; set; }
        public string message { get; set; }
        public T data { get; set; }
    }

    public class MaterialPageResult
    {
        public int totalCount { get; set; }
        public List<MaterialModel> pageDatas { get; set; }
        public string message { get; set; }
        public object data { get; set; }
        public int code { get; set; }
    }
}
